package il.ac.tau.cvws.scrabblesidekick.client.ext;

import android.app.Activity;
import android.os.Bundle;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;

public class FacebookExtension
{
	private static final String APP_ID 				= "112605918892286";
	
	private static final String PUBLISH_PERMISSION	= "publish_stream";
	private static final String USER_FEED_URL		= "me/feed";
	private static final String HTTP_POST			= "POST";
	
	private static final String PARAM_NAME			= "name";
	private static final String PARAM_MESSAGE		= "message";
	private static final String PARAM_LINK			= "link";
	private static final String PARAM_DESCRIPTION	= "description";
	private static final String PARAM_ICON			= "icon";
	private static final String PARAM_PICTURE		= "picture";
	
	private static final String POST_TITLE			= "Scrabble Ninja";
	private static final String POST_MESSAGE_FORMAT	= "Scrabble Ninja helped me with the word '%s'!";
	private static final String POST_DESCRIPTION	= "Scrabble Ninja is there for you when you just can't seem to find the right word!";
	private static final String POST_WEBSITE_URL	= "http://www.scrabbleninja.com";
	private static final String POST_PICTURE_URL	= "http://i.imgur.com/j7PiZ.png";
	
	private static FacebookExtension instance;
	
	public static FacebookExtension instance()
	{
		if (instance == null)
		{
			instance = new FacebookExtension(APP_ID);
		}
		
		return instance;
	}
	
	private final Facebook facebook;
	
	public FacebookExtension(String appId)
	{
		facebook = new Facebook(appId);
	}
	
	public void postSolution(
			final Activity activity,
			final String word,
			final Callback callback)
	{
		facebook.authorize(activity,
				new String[] { PUBLISH_PERMISSION },
				new Facebook.DialogListener()
		{
			@Override
			public void onFacebookError(FacebookError e)
			{
				callback.onFailure();
			}
			
			@Override
			public void onError(DialogError e)
			{
				callback.onFailure();
			}
			
			@Override
			public void onComplete(Bundle values)
			{
				try
				{
					Bundle params = new Bundle();
					
					params.putString(PARAM_NAME, POST_TITLE);
					params.putString(PARAM_MESSAGE, String.format(POST_MESSAGE_FORMAT, word));
					params.putString(PARAM_LINK, POST_WEBSITE_URL);
					params.putString(PARAM_DESCRIPTION, POST_DESCRIPTION);
					params.putString(PARAM_ICON, POST_PICTURE_URL);
					params.putString(PARAM_PICTURE, POST_PICTURE_URL);
					
					facebook.request(USER_FEED_URL, params, HTTP_POST);
					
					callback.onSuccess();
				}
				catch (Exception e)
				{
					callback.onFailure();
				}
			}
			
			@Override
			public void onCancel()
			{
				callback.onCancel();
			}
		});
	}
	
	public static interface Callback
	{
		public void onSuccess();
		public void onFailure();
		public void onCancel();
	}
}
